package com.hh.service.service.impl.message.producer;

import com.alibaba.fastjson.JSON;
import com.hh.common.config.RabbitMqConfig;
import com.hh.common.dto.RegisterImAccountDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class UserImProducerMessage {

//    @Autowired
//    private RabbitTemplate rabbitTemplate;

    @Resource
    private ApplicationContext applicationContext;

    /**
     * 生产用户注册IM账号消息
     * @param registerImAccountDTO
     */
    public void registerImAccount(RegisterImAccountDTO registerImAccountDTO) {
        RabbitTemplate rabbitTemplate = (RabbitTemplate) applicationContext.getBean("rabbitTemplate");
        //设置Confirms的异步回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                if(!ack){
                    log.error("IM账号为："+correlationData.getId()+"的注册消息送达交换机失败~");
                    //记录到数据库，后续做补偿处理
                    //todo
                }
            }
        });

        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returned) {
                //走到这个回调中就代表消息没有成功路由到指定队列，需要进补救，消息重发
                String message = new String(returned.getMessage().getBody());
                RegisterImAccountDTO messageDTO = JSON.parseObject(message, RegisterImAccountDTO.class);
                log.error("IM账号为："+messageDTO.getImUserId()+"的注册消息路由到队列失败~");
                //记录到数据库，后续做补偿处理
                //todo
            }
        });


        rabbitTemplate.convertAndSend(RabbitMqConfig.IM_EXCHANGE,RabbitMqConfig.IM_USER_REGISTER_QUEUE,registerImAccountDTO,new MessagePostProcessor(){
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置消息持久化（PERSISTENT表示持久化）
                message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                return message;
            }
        },new CorrelationData(registerImAccountDTO.getImUserId()));
    }
}
